package com.ncloud.crm.service.impl;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import com.ncloud.common.utils.RedisUtils;
import com.ncloud.crm.common.Constant;
import com.ncloud.crm.entity.*;
import com.ncloud.crm.entity.order.OrderNode;
import com.ncloud.crm.service.*;
import com.ncloud.crm.utils.ItemInfoUtils;
import com.ncloud.crm.utils.TableIdDefineUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.session.SessionProperties;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ncloud.crm.mapper.BsNodeMapper;

/**
 * Created by shiqiang on 2017/4/17.
 */
@Service
public class BsNodeServiceImpl implements BsNodeService {
	private static final String REDIS_KEY="bsDiscntInstId";
	@Autowired
	private BsNodeMapper nodeMapper;
	@Autowired
	private BsNodeEqptService eqptService;
	@Autowired
	private BsNodeNetAccessService accessService;
	@Autowired
	private BsNodeAttrService attrService;
	@Autowired
	private BsPublicCloudService pubCloudService;
	@Autowired
	private BsPublicCloudSegService bsPublicCloudSegService;
	@Autowired
	private BsDiscntFeeService bsDiscntFeeService;
	@Autowired
	private RedisUtils redisUtils;
    @Override
    public BsNode getNodeInfoByPk(Long nodeInstId) {
        return nodeMapper.getNodeInfoByPk(nodeInstId);
    }
    
    @Override
    public BsNode getNodeInfoByNodeId(Long nodeId) {
        return nodeMapper.getNodeInfoByNodeId(nodeId);
    }
    
    @Override
    public BsNode getBsNodeInfoByNodeId(Long nodeId) {
        return nodeMapper.getBsNodeInfoByNodeId(nodeId);
    }    
    
	@Override
	public int insertNode(BsNode node) {
		return nodeMapper.insertNode(node);		
	}

	@Override
	public int updateNode(BsNode node) {
		return nodeMapper.updateNode(node);
	}
	
	public JSONObject getNodeDetailInfo(Long nodeId) {
		BsNode node = getNodeInfoByNodeId(nodeId);
		List<BsNodeNetAccess> nodeAccesses = accessService.getNodeNetAccesses(nodeId);
		JSONObject nodeJson = new JSONObject();
		if(node != null){
			List<BsNodeAttr> nodeAttrs = attrService.getBsNodeAttrs(nodeId);
			nodeJson = JSON.parseObject(JSON.toJSONString(node,SerializerFeature.WriteMapNullValue));
			JSONArray nodeAttrArray = JSON.parseArray(JSON.toJSONString(nodeAttrs,SerializerFeature.WriteMapNullValue));
			if(nodeAttrArray !=null && nodeAttrArray.size()>0){
				setAttr2Object(nodeAttrArray,nodeJson);
			}
			/*接入信息isp*/
			if(nodeAccesses != null && nodeAccesses.size()>0){
				JSONObject netAccessJson = new JSONObject();
				for(BsNodeNetAccess access: nodeAccesses){
					if("1".equals(access.getNetType())){
						netAccessJson.put("lan",JSON.parseObject(JSON.toJSONString(access)));
					}else if("0".equals(access.getNetType())){
						netAccessJson.put("wan",JSON.parseObject(JSON.toJSONString(access)));
					}
				}
				nodeJson.put("isp",netAccessJson);
				//nodeJson.put("isp", JSON.parseArray(JSON.toJSONString(nodeAccesses,SerializerFeature.WriteMapNullValue)));
			}
			/*套餐费用信息*/
			JSONObject feeInfo = null;
			if(redisUtils.exists(REDIS_KEY+node.getDiscntInstId())){
				feeInfo = redisUtils.getBean(REDIS_KEY+node.getDiscntInstId(),JSONObject.class);
			}else{
				feeInfo = new JSONObject();
				BsDiscntFee bsDiscntFee = bsDiscntFeeService.getDiscntFeeByK(node.getDiscntInstId());
				if(bsDiscntFee !=null ){
					feeInfo.put("billingCycle",bsDiscntFee.getBillingCycle());
					feeInfo.put("cycleUnit",bsDiscntFee.getCycleUnit());
					feeInfo.put("standard",ItemInfoUtils.getDivideMoney(bsDiscntFee.getStandard(),100));
					feeInfo.put("balance",ItemInfoUtils.getDivideMoney(bsDiscntFee.getBalance(),100));
					/*BsNodeAttr param = new BsNodeAttr();
					param.setAttrType(Constant.ATTR_TYPE_NODE);
					param.setNodeId(node.getNodeId());
					param.setAttrCode("bandWidth");
					BsNodeAttr bsNodeAttr = attrService.getNodeAttrByPk(param);
					feeInfo.put("bandWidth",bsNodeAttr!=null?bsNodeAttr.getAttrValue():"");*/
					redisUtils.set(REDIS_KEY+node.getDiscntInstId(),feeInfo,3600L);
				}
				/* receiveFee:receivedFee,payFee:payFee,balance:balance,standard:standard,billingCycle:billingCycle,cycleUnit:cycleUnit*/
			}
			if(feeInfo!=null){
				nodeJson.putAll(feeInfo);
			}
			/*套餐费用信息end*/
			//CPE设备
			if(Constant.NODE_TYPE_1.equals(node.getNodeType()) && Constant.NODE_TYPE_CPE_1.equals(node.getNodeSubType())){
				List<BsNodeEqpt> nodeEqpts = eqptService.getNodeEqptsByNodeId(nodeId);
				if(nodeEqpts != null && nodeEqpts.size()>0){
					nodeJson.put("equip",JSON.parseObject(JSON.toJSONString(nodeEqpts.get(0),SerializerFeature.WriteMapNullValue)));
				}
			}
			//CLOUD信息
			if(Constant.NODE_TYPE_0.equals(node.getNodeType()) && Constant.NODE_TYPE_CLOUD_VPC_0.equals(node.getNodeSubType())){
				List<BsPublicCloud> publicClouds = pubCloudService.getNodeCloudByNodeId(nodeId);
				if(publicClouds != null && publicClouds.size()>0){
					JSONObject cloud = JSON.parseObject(JSON.toJSONString(publicClouds.get(0)));
					Long cloudId = cloud.getLong(TableIdDefineUtils.CLOUD_ID);
					List<BsCloudIpseg>  segList = bsPublicCloudSegService.getCloudIpSegByCloudId(cloudId);
					if(segList != null && segList.size()>0){
						cloud.put("ipseg",JSON.parseArray(JSON.toJSONString(segList)));
					}
					nodeJson.put("cloud",cloud);
				}
			}
			//VCEP 后续
		}

		return nodeJson;
	}
	
	public JSONObject getBsNodeDetailInfo(OrderNode orderNode) {
		Long nodeId=orderNode.getNodeId();
		BsNode node = getNodeInfoByNodeId(nodeId);
		List<BsNodeNetAccess> nodeAccesses = accessService.getNodeNetAccesses(nodeId);
		JSONObject nodeJson = new JSONObject();		
		if(node != null){	
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String createDate=sdf.format(orderNode.getCreateDate());
			List<BsNodeAttr> nodeAttrs = attrService.getNodeAttrs(nodeId);
			nodeJson = JSON.parseObject(JSON.toJSONString(node,SerializerFeature.WriteMapNullValue));
			JSONArray nodeAttrArray = JSON.parseArray(JSON.toJSONString(nodeAttrs,SerializerFeature.WriteMapNullValue));
			if(nodeAttrArray !=null && nodeAttrArray.size()>0){
				setAttr2Object(nodeAttrArray,nodeJson);
			}
			nodeJson.put("orderSate",orderNode.getOrderState());//订单状态
			nodeJson.put("constructItem",orderNode.getConstructItem());//施工环节
			nodeJson.put("constructUser",orderNode.getConstructUser());//施工人ID
			nodeJson.put("name",orderNode.getName());//施工人
			nodeJson.put("email",orderNode.getEmail());//施工email
			nodeJson.put("mobile",orderNode.getMobile());//施工mobile
			nodeJson.put("telephone",orderNode.getTelephone());//施工teleph
			nodeJson.put("createDate",createDate);//订单创建日期
			/*接入信息isp*/
			if(nodeAccesses != null && nodeAccesses.size()>0){
				JSONObject netAccessJson = new JSONObject();
				for(BsNodeNetAccess access: nodeAccesses){
					if("1".equals(access.getNetType())){
						netAccessJson.put("lan",JSON.parseObject(JSON.toJSONString(access)));
					}else if("0".equals(access.getNetType())){
						netAccessJson.put("wan",JSON.parseObject(JSON.toJSONString(access)));
					}
				}
				nodeJson.put("isp",netAccessJson);
				//nodeJson.put("isp", JSON.parseArray(JSON.toJSONString(nodeAccesses,SerializerFeature.WriteMapNullValue)));
			}
			/*套餐费用信息*/
			JSONObject feeInfo = null;
			if(redisUtils.exists(REDIS_KEY+node.getDiscntInstId())){
				feeInfo = redisUtils.getBean(REDIS_KEY+node.getDiscntInstId(),JSONObject.class);
			}else{
				feeInfo = new JSONObject();
				BsDiscntFee bsDiscntFee = bsDiscntFeeService.getDiscntFeeByK(node.getDiscntInstId());
				if(bsDiscntFee !=null ){
					feeInfo.put("billingCycle",bsDiscntFee.getBillingCycle());
					feeInfo.put("cycleUnit",bsDiscntFee.getCycleUnit());
					feeInfo.put("standard",ItemInfoUtils.getDivideMoney(bsDiscntFee.getStandard(),100));
					feeInfo.put("balance",ItemInfoUtils.getDivideMoney(bsDiscntFee.getBalance(),100));
					redisUtils.set(REDIS_KEY+node.getDiscntInstId(),feeInfo,3600L);
				}
			}
			if(feeInfo!=null){
				nodeJson.putAll(feeInfo);
			}
			/*套餐费用信息end*/
			//CPE设备
			if(Constant.NODE_TYPE_1.equals(node.getNodeType()) && Constant.NODE_TYPE_CPE_1.equals(node.getNodeSubType())){
				List<BsNodeEqpt> nodeEqpts = eqptService.getNodeEqptsByNodeId(nodeId);
				if(nodeEqpts != null && nodeEqpts.size()>0){
					nodeJson.put("equip",JSON.parseObject(JSON.toJSONString(nodeEqpts.get(0),SerializerFeature.WriteMapNullValue)));
				}
			}
			//CLOUD信息
			if(Constant.NODE_TYPE_0.equals(node.getNodeType()) && Constant.NODE_TYPE_CLOUD_VPC_0.equals(node.getNodeSubType())){
				List<BsPublicCloud> publicClouds = pubCloudService.getNodeCloudByNodeId(nodeId);
				if(publicClouds != null && publicClouds.size()>0){
					JSONObject cloud = JSON.parseObject(JSON.toJSONString(publicClouds.get(0)));
					Long cloudId = cloud.getLong(TableIdDefineUtils.CLOUD_ID);
					List<BsCloudIpseg>  segList = bsPublicCloudSegService.getCloudIpSegByCloudId(cloudId);
					if(segList != null && segList.size()>0){
						cloud.put("ipseg",JSON.parseArray(JSON.toJSONString(segList)));
					}
					nodeJson.put("cloud",cloud);
				}
			}
			//VCEP 后续
		}

		return nodeJson;
	}
	
	public JSONObject getBsONodeDetailInfo(OrderNode orderNode) {
		Long nodeId=orderNode.getNodeId();
		BsNode node = getBsNodeInfoByNodeId(nodeId);
		List<BsNodeNetAccess> nodeAccesses = accessService.getBsNodeNetAccesses(nodeId);
		JSONObject nodeJson = new JSONObject();		
		if(node != null){	
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String createDate=sdf.format(orderNode.getCreateDate());
			List<BsNodeAttr> nodeAttrs = attrService.getBsNodeAttrs(nodeId);
			nodeJson = JSON.parseObject(JSON.toJSONString(node,SerializerFeature.WriteMapNullValue));
			JSONArray nodeAttrArray = JSON.parseArray(JSON.toJSONString(nodeAttrs,SerializerFeature.WriteMapNullValue));
			if(nodeAttrArray !=null && nodeAttrArray.size()>0){
				setAttr2Object(nodeAttrArray,nodeJson);
			}
			nodeJson.put("orderSate",orderNode.getOrderState());//订单状态
			nodeJson.put("constructItem",orderNode.getConstructItem());//施工环节
			nodeJson.put("constructUser",orderNode.getConstructUser());//施工人
			nodeJson.put("name",orderNode.getName());//施工人
			nodeJson.put("email",orderNode.getEmail());//施工email
			nodeJson.put("mobile",orderNode.getMobile());//施工mobile
			nodeJson.put("telephone",orderNode.getTelephone());//施工teleph
			nodeJson.put("createDate",createDate);//订单创建日期
			/*接入信息isp*/
			if(nodeAccesses != null && nodeAccesses.size()>0){
				JSONObject netAccessJson = new JSONObject();
				for(BsNodeNetAccess access: nodeAccesses){
					if("1".equals(access.getNetType())){
						netAccessJson.put("lan",JSON.parseObject(JSON.toJSONString(access)));
					}else if("0".equals(access.getNetType())){
						netAccessJson.put("wan",JSON.parseObject(JSON.toJSONString(access)));
					}
				}
				nodeJson.put("isp",netAccessJson);
			}
			/*套餐费用信息*/
			JSONObject feeInfo = null;
			if(redisUtils.exists(REDIS_KEY+node.getDiscntInstId())){
				feeInfo = redisUtils.getBean(REDIS_KEY+node.getDiscntInstId(),JSONObject.class);
			}else{
				feeInfo = new JSONObject();
				BsDiscntFee bsDiscntFee = bsDiscntFeeService.getDiscntOFeeByK(node.getDiscntInstId());
				if(bsDiscntFee !=null ){
					feeInfo.put("billingCycle",bsDiscntFee.getBillingCycle());
					feeInfo.put("cycleUnit",bsDiscntFee.getCycleUnit());
					feeInfo.put("standard",ItemInfoUtils.getDivideMoney(bsDiscntFee.getStandard(),100));
					feeInfo.put("balance",ItemInfoUtils.getDivideMoney(bsDiscntFee.getBalance(),100));
					redisUtils.set(REDIS_KEY+node.getDiscntInstId(),feeInfo,3600L);
				}
					}
			if(feeInfo!=null){
				nodeJson.putAll(feeInfo);
			}
			/*套餐费用信息end*/
			//CPE设备
			if(Constant.NODE_TYPE_1.equals(node.getNodeType()) && Constant.NODE_TYPE_CPE_1.equals(node.getNodeSubType())){
				List<BsNodeEqpt> nodeEqpts = eqptService.getBsNodeEqptsByNodeId(nodeId);
				if(nodeEqpts != null && nodeEqpts.size()>0){
					nodeJson.put("equip",JSON.parseObject(JSON.toJSONString(nodeEqpts.get(0),SerializerFeature.WriteMapNullValue)));
				}
			}
			//CLOUD信息
			if(Constant.NODE_TYPE_0.equals(node.getNodeType()) && Constant.NODE_TYPE_CLOUD_VPC_0.equals(node.getNodeSubType())){
				List<BsPublicCloud> publicClouds = pubCloudService.getBsNodeCloudByNodeId(nodeId);
				if(publicClouds != null && publicClouds.size()>0){
					JSONObject cloud = JSON.parseObject(JSON.toJSONString(publicClouds.get(0)));
					Long cloudId = cloud.getLong(TableIdDefineUtils.CLOUD_ID);
					List<BsCloudIpseg>  segList = bsPublicCloudSegService.getCloudIpSegByCloudId(cloudId);
					if(segList != null && segList.size()>0){
						cloud.put("ipseg",JSON.parseArray(JSON.toJSONString(segList)));
					}
					nodeJson.put("cloud",cloud);
				}
			}
			//VCEP 后续
		}

		return nodeJson;
	}
	
	
	private void setAttr2Object(JSONArray nodeAttrArray, JSONObject nodeJson) {
    	if(nodeAttrArray == null || nodeAttrArray.isEmpty() || nodeAttrArray.size()<=0) return;
		for(int i=0;i<nodeAttrArray.size();i++){
			JSONObject attr = nodeAttrArray.getJSONObject(i);
			String key = attr.getString("attrCode");
			String value = ItemInfoUtils.isMoney(key)?String.valueOf(ItemInfoUtils.getDivideMoney(attr.getLong("attrValue"),100)):attr.getString("attrValue");
			nodeJson.put(key,value);
		}
	}

	@Override
	public List<BsNode> getNodesByCust(Long custId) {
		return nodeMapper.getBsNodesByCust(custId);
	}

	@Override
	public List<OrderNode> getBsNodesByOrder(Long orderId) {		
		return nodeMapper.getBsNodesByOrder(orderId);
	}

	@Override
	public JSONObject getNodeMapInfoByCode(String nodeCode, Long custId) {
		JSONObject result = new JSONObject();
		Map<String,Object> map = nodeMapper.getBsNodeByCode(nodeCode,custId);
		result.putAll(map);
		return result;
	}
}